package cn.kgc.controller.paycontroller;

import cn.kgc.config.AlipayConfig;
import cn.kgc.dao.mapper.ItripHotelOrderMapper;
import cn.kgc.dao.mapper.ItripHotelTempStoreMapper;
import cn.kgc.dao.mapper.ItripTradeEndsMapper;
import cn.kgc.dtos.Dto;
import cn.kgc.pojo.ItripHotelOrder;
import cn.kgc.pojo.ItripHotelTempStore;
import cn.kgc.service.ItripHotelOrderPayService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;

@RestController
@RequestMapping("/api")
@Api(value = "这是支付模块类",tags = {"dw"})
public class AlipayController {

    @Resource
    private ItripHotelOrderMapper itripHotelOrderMapper;

    @Resource
    private ItripTradeEndsMapper itripTradeEndsMapper;
    @Resource
    private ItripHotelTempStoreMapper itripHotelTempStoreMapper;

    //支付宝
    @RequestMapping(value = "/prepay/{orderNo}",method = RequestMethod.GET)
    @ApiOperation(value = "支付",httpMethod ="POST")
    public void alipay(@PathVariable String orderNo,HttpServletResponse response) {

        ItripHotelOrder itripHotelOrder= itripHotelOrderMapper.selectOrderByorderNo(orderNo);
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        //订单描述
        model.setBody("付款中心-订单付款");
        //订单标题
        model.setSubject("旅行付款");
        //商户订单号,64个字符以内、可包含字母、数字、下划线；需保证在商户端不重复
        model.setOutTradeNo(itripHotelOrder.getOrderNo());
        //订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]。
        model.setTotalAmount(itripHotelOrder.getPayAmount()+"");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        alipayRequest.setReturnUrl("http://localhost/#/orderpaystate/?orderNo="+itripHotelOrder.getOrderNo()+"&id="+itripHotelOrder.getId());
        alipayRequest.setBizModel(model);
        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //设置这个result是一个页面内容 而不是一个字符串
        response.setContentType("text/html;charset=utf-8");
        try {
            response.getWriter().write(result);//付款 页面
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //异步回调函数
    @RequestMapping(value = "/notifyCall",method = RequestMethod.POST)
    @ApiOperation(value = "支付",httpMethod ="POST")
    public void AlipayNotify(HttpServletRequest request,HttpServletResponse response) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        String out_trade_no = null;
        String trade_no = null;
        String trade_status = null;
        try {
            //商户订单号
            out_trade_no= new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            trade_no= new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //交易状态
            trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = false;
        try {
            verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, "RSA2");
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        if(!verify_result){//验证成功
            //请在这里加上商户的业务逻辑程序代码
            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            ItripHotelOrder itripHotelOrder= itripHotelOrderMapper.selectOrderByorderNo(out_trade_no);
            long hotelId=itripHotelOrder.getHotelId();
            long roomId=itripHotelOrder.getRoomId();
            if(trade_status.equals("TRADE_FINISHED")&&itripHotelOrder!=null){
                //业务逻辑
                pqy(out_trade_no,hotelId,roomId,itripHotelOrder);
            } else if (trade_status.equals("TRADE_SUCCESS")&&itripHotelOrder!=null){
                //业务逻辑
                pqy(out_trade_no,hotelId,roomId,itripHotelOrder);
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            //out.clear();
            out.flush();
            out.println("success");	//请不要修改或删除
        }else{//验证失败
            out.println("fail");
        }
    }


    public void  pqy(String out_trade_no,long hotelId,long roomId,ItripHotelOrder itripHotelOrder){
        //数据库增加一条消费信息信息
        itripTradeEndsMapper.insert(out_trade_no);
        //查询库存表是否已有数据
        List<ItripHotelTempStore> list = itripHotelTempStoreMapper.selectByPrimaryKey(hotelId,roomId);
        //构建数据
        ItripHotelTempStore itripHotelTempStore1=new ItripHotelTempStore();
        itripHotelTempStore1.setHotelId(hotelId);
        itripHotelTempStore1.setRoomId(roomId);
        int num=0;
        //判断库存表是否已有数据
        if (list.size()==0){
            itripHotelTempStore1.setStore(20);
            itripHotelTempStore1.setRecordDate(new Date());
            itripHotelTempStore1.setCreationDate(new Date());
            //没有增加一条数据
            num= itripHotelTempStoreMapper.insert(itripHotelTempStore1);
        }else{
            itripHotelTempStore1.setStore(list.get(0).getStore());
            //构建数据
            itripHotelTempStore1.setCreationDate(list.get(0).getCreationDate());
            itripHotelTempStore1.setRecordDate(new Date());
            //添加一条库存信息
            num=itripHotelTempStoreMapper.insert(itripHotelTempStore1);
        }
        if (num>0){
         /*   //修改库存数量
            itripHotelTempStoreMapper.updatestoreByid(hotelId,roomId,itripHotelOrder.getCount());*/
            //修改订单状态
            itripHotelOrderMapper.updateByPrimaryKey(out_trade_no);
        }
    }
}
